﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using System.IO;

namespace Method.SmartMeter.Controllers
{

    /*
     * 用于模板文件下载 —— Anthony
     */

    [Route("api/[controller]")]
    [ApiController]
    public class DownLoadFileController : Controller
    {

        private readonly IHostingEnvironment _hostingEnvironment;

        public DownLoadFileController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpGet]
        public FileResult Get()
        {
            try
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                var files = Directory.GetFiles(webRootPath, "*.xlsx");
                if (files?.Length > 0)
                {
                    foreach (var file in files)
                    {
                        if (!string.IsNullOrWhiteSpace(file) && file.Contains("模板"))
                        {
                            var stream = System.IO.File.OpenRead(file);
                            var provider = new FileExtensionContentTypeProvider();
                            var fileType = provider.Mappings[".xlsx"];
                            return File(stream, fileType, Path.GetFileName(file));
                        }
                    }
                }

            }
            catch (System.Exception)
            {

                //throw;
            }

            return new FileContentResult(new byte[] { }, "XLSX");

        }
    }
}